package com.cyy.springbootinit.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cyy.springbootinit.annotation.AuthCheck;
import com.cyy.springbootinit.common.BaseResponse;
import com.cyy.springbootinit.common.DeleteRequest;
import com.cyy.springbootinit.common.ErrorCode;
import com.cyy.springbootinit.common.ResultUtils;
import com.cyy.springbootinit.constant.UserConstant;
import com.cyy.springbootinit.exception.BusinessException;
import com.cyy.springbootinit.exception.ThrowUtils;
import com.cyy.springbootinit.model.dto.equipmentdata.EquipmentDataAddRequest;
import com.cyy.springbootinit.model.dto.equipmentdata.EquipmentDataEditRequest;
import com.cyy.springbootinit.model.dto.equipmentdata.EquipmentDataQueryRequest;
import com.cyy.springbootinit.model.dto.equipmentdata.EquipmentDataUpdateRequest;
import com.cyy.springbootinit.model.entity.*;
import com.cyy.springbootinit.model.vo.EquipmentDataVO;
import com.cyy.springbootinit.service.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 设备数据表接口
 *
 * @author 程序员cyy</a>
 * @from cyy</a>
 */
@RestController
@RequestMapping("/equipmentData")
@Slf4j
public class EquipmentDataController {
    @Resource
    private EquipmentDataService equipmentDataService;
    @Resource
    private UserService userService;

    // region 增删改查

    //用户缴费
    @PostMapping("/pay")
    public BaseResponse<Boolean> pay(Double money,Integer equipmentId, HttpServletRequest request) {
        ThrowUtils.throwIf(money == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(equipmentId == null, ErrorCode.PARAMS_ERROR);
        return  ResultUtils.success(equipmentDataService.pay(money,equipmentId,request));
    }
    /**
     * 创建设备数据表
     *
     * @param equipmentDataAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addEquipmentData(@RequestBody EquipmentDataAddRequest equipmentDataAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(equipmentDataAddRequest == null, ErrorCode.PARAMS_ERROR);
        // todo 在此处将实体类和 DTO 进行转换
        EquipmentData equipmentData = new EquipmentData();
        BeanUtils.copyProperties(equipmentDataAddRequest, equipmentData);
        // 数据校验
        equipmentDataService.validEquipmentData(equipmentData, true);
        // todo 填充默认值
        User loginUser = userService.getLoginUser(request);
        // 写入数据库
        boolean result = equipmentDataService.save(equipmentData);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newEquipmentDataId = equipmentData.getDataId();
        return ResultUtils.success(newEquipmentDataId);
    }

    /**
     * 删除设备数据表
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteEquipmentData(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        EquipmentData oldEquipmentData = equipmentDataService.getById(id);
        ThrowUtils.throwIf(oldEquipmentData == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if ( !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = equipmentDataService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 更新设备数据表（仅管理员可用）
     *
     * @param equipmentDataUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateEquipmentData(@RequestBody EquipmentDataUpdateRequest equipmentDataUpdateRequest) {
        if (equipmentDataUpdateRequest == null || equipmentDataUpdateRequest.getDataId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        EquipmentData equipmentData = new EquipmentData();
        BeanUtils.copyProperties(equipmentDataUpdateRequest, equipmentData);
        // 数据校验
        equipmentDataService.validEquipmentData(equipmentData, false);
        // 判断是否存在
        long id = equipmentDataUpdateRequest.getDataId();
        EquipmentData oldEquipmentData = equipmentDataService.getById(id);
        ThrowUtils.throwIf(oldEquipmentData == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = equipmentDataService.updateById(equipmentData);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取设备数据表（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<EquipmentDataVO> getEquipmentDataVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        EquipmentData equipmentData = equipmentDataService.getById(id);
        ThrowUtils.throwIf(equipmentData == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return ResultUtils.success(equipmentDataService.getEquipmentDataVO(equipmentData, request));
    }

    @GetMapping("/get/VoByUserId")
    public BaseResponse<List<EquipmentDataVO>> getEquipmentDataVOByUserId(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_FOUND_ERROR);
        //Long D= loginUser.getId();
        Integer dormitoryId = loginUser.getDormitoryId();
        return ResultUtils.success(equipmentDataService.getEquipmentDataVoByDormitoryId(dormitoryId));
    }

    /**
     * 分页获取设备数据表列表（仅管理员可用）
     *
     * @param equipmentDataQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<EquipmentData>> listEquipmentDataByPage(@RequestBody EquipmentDataQueryRequest equipmentDataQueryRequest) {
        long current = equipmentDataQueryRequest.getCurrent();
        long size = equipmentDataQueryRequest.getPageSize();
        // 查询数据库
        Page<EquipmentData> equipmentDataPage = equipmentDataService.page(new Page<>(current, size),
                equipmentDataService.getQueryWrapper(equipmentDataQueryRequest));
        return ResultUtils.success(equipmentDataPage);
    }

    /**
     * 分页获取设备数据表列表（封装类）
     *
     * @param equipmentDataQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<EquipmentDataVO>> listEquipmentDataVOByPage(@RequestBody EquipmentDataQueryRequest equipmentDataQueryRequest,
                                                               HttpServletRequest request) {
        long current = equipmentDataQueryRequest.getCurrent();
        long size = equipmentDataQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<EquipmentData> equipmentDataPage = equipmentDataService.page(new Page<>(current, size),
                equipmentDataService.getQueryWrapper(equipmentDataQueryRequest));
        // 获取封装类
        return ResultUtils.success(equipmentDataService.getEquipmentDataVOPage(equipmentDataPage, request));
    }

    /**
     * 分页获取当前登录用户创建的设备数据表列表
     *
     * @param equipmentDataQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<EquipmentDataVO>> listMyEquipmentDataVOByPage(@RequestBody EquipmentDataQueryRequest equipmentDataQueryRequest,
                                                                 HttpServletRequest request) {
        ThrowUtils.throwIf(equipmentDataQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        long current = equipmentDataQueryRequest.getCurrent();
        long size = equipmentDataQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<EquipmentData> equipmentDataPage = equipmentDataService.page(new Page<>(current, size),
                equipmentDataService.getQueryWrapper(equipmentDataQueryRequest));
        // 获取封装类
        return ResultUtils.success(equipmentDataService.getEquipmentDataVOPage(equipmentDataPage, request));
    }

    /**
     * 编辑设备数据表（给用户使用）
     *
     * @param equipmentDataEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editEquipmentData(@RequestBody EquipmentDataEditRequest equipmentDataEditRequest, HttpServletRequest request) {
        if (equipmentDataEditRequest == null || equipmentDataEditRequest.getDataId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // todo 在此处将实体类和 DTO 进行转换
        EquipmentData equipmentData = new EquipmentData();
        BeanUtils.copyProperties(equipmentDataEditRequest, equipmentData);
        // 数据校验
        equipmentDataService.validEquipmentData(equipmentData, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = equipmentDataEditRequest.getDataId();
        EquipmentData oldEquipmentData = equipmentDataService.getById(id);
        ThrowUtils.throwIf(oldEquipmentData == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if ( !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = equipmentDataService.updateById(equipmentData);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    // endregion
}
